<?php
/*********************************************
  Copyright (c) 2012 by DragonflyCMS team
  http://dragonflycms.org
  Released under GNU GPL version 2 or any later version
**********************************************/

class Html_Form
{
	public static function element($id, $item)
	{
		static $loaded_vals;
		$name = $id;
		$data = '';
		$extra = $text = false;
		$options = isset($item['items_options']) ? explode(',', $item['items_options']) : array();
		array_walk($options, 'trim');
		if (0 === strpos($id, 'item-text-only')) {
			$text = $item;
		}
		else if (0 === strpos($id, 'item-extra-data')) {
			$extra = $item;
			$id = 'extra';
		}
		else if (false !== strpos($id, '[]')) {
			isset($loaded_vals[$name]) ? ++$loaded_vals[$name] : $loaded_vals[$name] = 0;
			$id = str_replace('[]', $loaded_vals[$name], $name);
		}
		if (!$text) {
			if (!isset($item['value'])) $item['value'] = '';
			if (!empty($item['required'])) $item['title'] = $item['title'].'*';
			switch ($item['type']) {
			case 'button':
				$data = '<input type="button" id="'.$id.'" value="'.$item['value'].'"';
				$data .= !empty($item['extra']) ? ' '.$item['extra'] : '';
				$data .= '/>';
				break;
			case 'text':
				$data = '<input type="text" id="'.$id.'" name="'.$name.'" value="'.$item['value'].'"';
				if (!empty($item['maxlength'])) { $data .= ' maxlength="'.intval($item['maxlength']).'"'; }
				if (!empty($item['size'])) { $data .= ' size="'.intval($item['size']).'"'; }
				if (!empty($item['extra'])) $data .= ' '.$item['extra'];
				$data .= '/>';
				break;
			case 'select':
				$data = select_box($id, $item['value'], $item['options']);
				break;
			case 'yesno':
				$data = yesno_option($id, $MAIN_CFG['_security'][$id]);
				break;
			case 'textarea':
				$data = '<textarea id="'.$id.'" name="'.$name.'"';
				$data .= !empty($item['rows']) ? ' rows="'.intval($item['rows']).'"' : '';
				$data .= !empty($item['cols']) ? ' cols="'.intval($item['cols']).'"' : '';
				$data .= '></textarea>';
				break;
			case 'extra':
				break;
			default:
				continue;
			}
		}
		return array('data' => $data, 'extra' => $extra, 'text' => $text);
	}
}